package com.yesjava.springbootjpa.demo.service;

import com.yesjava.springbootjpa.demo.dao.CategoryDao;
import com.yesjava.springbootjpa.demo.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {
    @Autowired//Dao层注入到service层
            CategoryDao categoryDao;

    /**
     * 添加或更改类别实体对象
     *
     * @param category
     */
    public void saveOrUpdateCategory(Category category) {
        categoryDao.save(category);
    }

    /**
     * 查询所有的类别
     *
     * @return
     */
    public List<Category> findAll() {
        List<Category> all = categoryDao.findAll();
        return all;
    }


    /**
     * 查询所有的顶级类别
     *
     * @return
     */
    public List<Category> findAllTop() {
        List<Category> top = categoryDao.myFindTop();
        return top;
    }



    /**
     * 查询一个
     * @param id
     * @return
     */
    public Category findById(Integer id) {
        return categoryDao.findById(id).get();
    }

    /**
     * 删除一个
     *
     * @param category
     */
    public void deleteCategory(Category category) {
        categoryDao.deleteById(category.getId());
    }

    public void deleteCategoryById(Integer id) {
        categoryDao.deleteById(id);
    }


    /**
     * 批量删除
     * @param categories
     */
    public void deleteBacth(List<Category> categories) {
        categoryDao.deleteInBatch(categories);
    }




    /*
   递归方法,查询所有的子类别，常说的多级菜单问题
     */
    private List<Category> findCategoryAndChildredById(List<Category> categoryList, Category me) {
        //  Category me = this.findById(id);
        categoryList.add(me);
        if (me.getChildren() == null || me.getChildren().size() == 0) {
            return null;
        } else {
            List<Category> children = me.getChildren();
            for (Category child : children) {
                findCategoryAndChildredById(categoryList, child);
            }
        }
        return categoryList;
    }

    public List<Category> findCategoryAndChildredById(Integer id) {
        List<Category> list = new ArrayList<>();
        Category me = this.findById(id);
        if (me != null) {
            findCategoryAndChildredById(list, me);
        }
        return list;
    }

}
